{% extends 'base.html' %}

{% block title %}教练管理 - 乒乓球培训管理系统{% endblock %}

{% block page_title %}教练管理{% endblock %}

{% block extra_css %}
<style>
    .search-container {
        background: white;
        border-radius: 15px;
        padding: 1.5rem;
        margin-bottom: 2rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
    }

    .coach-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(380px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .coach-card {
        background: white;
        border-radius: 15px;
        padding: 1.5rem;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: all 0.3s ease;
        position: relative;
        border-left: 4px solid #e9ecef;
    }

    .coach-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }

    .coach-card.active {
        border-left-color: #28a745;
    }

    .coach-card.pending {
        border-left-color: #ffc107;
    }

    .coach-card.inactive {
        border-left-color: #dc3545;
    }

    .coach-header {
        display: flex;
        align-items: center;
        margin-bottom: 1rem;
    }

    .coach-avatar {
        width: 60px;
        height: 60px;
        border-radius: 50%;
        background: #f8f9fa;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 1rem;
        overflow: hidden;
    }

    .coach-avatar img {
        width: 100%;
        height: 100%;
        object-fit: cover;
    }

    .coach-avatar i {
        font-size: 1.5rem;
        color: #6c757d;
    }

    .coach-info {
        flex: 1;
    }

    .coach-name {
        font-size: 1.25rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
    }

    .coach-level {
        padding: 0.25rem 0.75rem;
        border-radius: 15px;
        font-size: 0.75rem;
        font-weight: 600;
        margin-top: 0.5rem;
        display: inline-block;
    }

    .level-senior {
        background: #e7f3ff;
        color: #0056b3;
    }

    .level-middle {
        background: #fff3cd;
        color: #856404;
    }

    .level-junior {
        background: #d4edda;
        color: #155724;
    }

    .coach-meta {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 1rem;
        padding-bottom: 1rem;
        border-bottom: 1px solid #f8f9fa;
    }

    .coach-campus {
        font-size: 0.875rem;
        color: #6c757d;
    }

    .coach-status {
        padding: 0.25rem 0.75rem;
        border-radius: 15px;
        font-size: 0.75rem;
        font-weight: 600;
    }

    .status-active {
        background: #d4edda;
        color: #155724;
    }

    .status-pending {
        background: #fff3cd;
        color: #856404;
    }

    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }

    .coach-stats {
        display: grid;
        grid-template-columns: repeat(3, 1fr);
        gap: 1rem;
        margin-bottom: 1rem;
    }

    .stat-item {
        text-align: center;
    }

    .stat-number {
        font-size: 1.25rem;
        font-weight: 700;
        color: #2c3e50;
        margin: 0;
    }

    .stat-label {
        font-size: 0.75rem;
        color: #6c757d;
        margin-top: 0.25rem;
    }

    .coach-rate {
        font-size: 1.1rem;
        font-weight: 600;
        color: #28a745;
        text-align: center;
        margin-bottom: 1rem;
    }

    .coach-actions {
        display: flex;
        gap: 0.5rem;
        justify-content: center;
    }

    .btn-action {
        padding: 0.375rem 0.75rem;
        border-radius: 6px;
        font-size: 0.875rem;
        text-decoration: none;
        transition: all 0.2s ease;
    }

    .btn-action:hover {
        transform: translateY(-1px);
    }

    .summary-cards {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
        gap: 1.5rem;
        margin-bottom: 2rem;
    }

    .summary-card {
        background: white;
        border-radius: 12px;
        padding: 1.5rem;
        text-align: center;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        border-left: 4px solid;
    }

    .summary-card.total { border-left-color: #007bff; }
    .summary-card.active { border-left-color: #28a745; }
    .summary-card.pending { border-left-color: #ffc107; }
    .summary-card.inactive { border-left-color: #dc3545; }

    .summary-number {
        font-size: 2rem;
        font-weight: 700;
        margin: 0;
    }

    .summary-label {
        color: #6c757d;
        font-size: 0.875rem;
        margin-top: 0.5rem;
    }

    .batch-toolbar {
        background: white;
        border-radius: 12px;
        padding: 1rem;
        margin-bottom: 1.5rem;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        display: none;
    }

    .batch-toolbar.active {
        display: block;
    }

    .selection-info {
        color: #007bff;
        font-weight: 600;
        margin-bottom: 1rem;
    }

    .empty-state {
        text-align: center;
        padding: 3rem;
        color: #6c757d;
    }

    .empty-state i {
        font-size: 3rem;
        margin-bottom: 1rem;
        opacity: 0.5;
    }

    @media (max-width: 768px) {
        .coach-grid {
            grid-template-columns: 1fr;
        }

        .summary-cards {
            grid-template-columns: repeat(2, 1fr);
        }

        .coach-stats {
            grid-template-columns: repeat(2, 1fr);
        }

        .search-container .row {
            flex-direction: column;
        }

        .search-container .col-md-3,
        .search-container .col-md-2 {
            margin-bottom: 1rem;
        }
    }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 搜索表单 -->
    <div class="search-container">
        <form method="GET" id="searchForm">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    {{ form.keyword.label(class="form-label") }}
                    {{ form.keyword(class="form-control") }}
                </div>

                <div class="col-md-2">
                    {{ form.campus_id.label(class="form-label") }}
                    {{ form.campus_id(class="form-select") }}
                </div>

                <div class="col-md-2">
                    {{ form.status.label(class="form-label") }}
                    {{ form.status(class="form-select") }}
                </div>

                <div class="col-md-2">
                    {{ form.coach_level.label(class="form-label") }}
                    {{ form.coach_level(class="form-select") }}
                </div>

                <div class="col-md-2">
                    {{ form.sort_by.label(class="form-label") }}
                    {{ form.sort_by(class="form-select") }}
                </div>

                <div class="col-md-1">
                    <button type="submit" class="btn btn-primary w-100">
                        <i class="bi bi-search"></i>
                    </button>
                </div>
            </div>
        </form>
    </div>

    <!-- 汇总统计卡片 -->
    <div class="summary-cards">
        <div class="summary-card total">
            <h3 class="summary-number" style="color: #007bff;">{{ summary.total }}</h3>
            <div class="summary-label">总教练数</div>
        </div>
        <div class="summary-card active">
            <h3 class="summary-number" style="color: #28a745;">{{ summary.active }}</h3>
            <div class="summary-label">在职教练</div>
        </div>
        <div class="summary-card pending">
            <h3 class="summary-number" style="color: #ffc107;">{{ summary.pending }}</h3>
            <div class="summary-label">待审核</div>
        </div>
        <div class="summary-card inactive">
            <h3 class="summary-number" style="color: #dc3545;">{{ summary.inactive }}</h3>
            <div class="summary-label">离职教练</div>
        </div>
    </div>

    <!-- 批量操作工具栏 -->
    <div class="batch-toolbar" id="batchToolbar">
        <div class="selection-info">
            已选择 <span id="selectedCount">0</span> 个教练
        </div>
        <form method="POST" action="{{ url_for('coaches.batch_operation') }}" id="batchForm">
            {{ csrf_token() }}
            <input type="hidden" name="coach_ids" id="selectedIds" value="">
            <div class="row g-3 align-items-end">
                <div class="col-md-3">
                    <label class="form-label">批量操作</label>
                    <select name="action" class="form-select" required>
                        <option value="">请选择操作</option>
                        <option value="activate">批量激活</option>
                        <option value="deactivate">批量停用</option>
                        <option value="set_level">设置级别</option>
                        <option value="transfer_campus">转移校区</option>
                        <option value="delete">批量删除</option>
                    </select>
                </div>

                <div class="col-md-2" id="levelField" style="display: none;">
                    <label class="form-label">目标级别</label>
                    <select name="target_level" class="form-select">
                        <option value="">请选择</option>
                        <option value="senior">高级教练</option>
                        <option value="middle">中级教练</option>
                        <option value="junior">初级教练</option>
                    </select>
                </div>

                <div class="col-md-2" id="campusField" style="display: none;">
                    <label class="form-label">目标校区</label>
                    <select name="target_campus_id" class="form-select">
                        <option value="">请选择</option>
                        {% for campus_id, campus_name in form.campus_id.choices %}
                            {% if campus_id %}
                            <option value="{{ campus_id }}">{{ campus_name }}</option>
                            {% endif %}
                        {% endfor %}
                    </select>
                </div>

                <div class="col-auto">
                    <button type="submit" class="btn btn-warning">执行操作</button>
                    <button type="button" class="btn btn-secondary" onclick="clearSelection()">取消选择</button>
                </div>
            </div>
        </form>
    </div>

    <!-- 教练列表 -->
    {% if coaches %}
    <div class="coach-grid">
        {% for coach in coaches %}
        <div class="coach-card {{ coach.status }}" data-coach-id="{{ coach.id }}">
            <!-- 选择框 -->
            <div class="position-absolute top-0 end-0 m-2">
                <input type="checkbox" class="form-check-input coach-checkbox" value="{{ coach.id }}">
            </div>

            <!-- 教练头部信息 -->
            <div class="coach-header">
                <div class="coach-avatar">
                    {% if coach.photo_url %}
                    <img src="{{ coach.photo_url }}" alt="{{ coach.real_name }}">
                    {% else %}
                    <i class="bi bi-person-circle"></i>
                    {% endif %}
                </div>
                <div class="coach-info">
                    <h5 class="coach-name">{{ coach.real_name }}</h5>
                    <div>
                        {% if coach.coach_level %}
                        <span class="coach-level level-{{ coach.coach_level }}">
                            {% if coach.coach_level == 'senior' %}高级教练
                            {% elif coach.coach_level == 'middle' %}中级教练
                            {% elif coach.coach_level == 'junior' %}初级教练
                            {% endif %}
                        </span>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 元信息 -->
            <div class="coach-meta">
                <div class="coach-campus">
                    <i class="bi bi-geo-alt me-1"></i>
                    {{ coach.campus.name if coach.campus else '未分配校区' }}
                </div>
                <span class="coach-status status-{{ coach.status }}">
                    {% if coach.status == 'active' %}在职
                    {% elif coach.status == 'pending' %}待审核
                    {% elif coach.status == 'inactive' %}离职
                    {% endif %}
                </span>
            </div>

            <!-- 费用信息 -->
            {% if coach.hourly_rate %}
            <div class="coach-rate">
                {{ coach.hourly_rate }}元/小时
            </div>
            {% endif %}

            <!-- 统计信息 -->
            <div class="coach-stats">
                <div class="stat-item">
                    <div class="stat-number">{{ coach.get_coach_students_count() }}</div>
                    <div class="stat-label">指导学员</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">{{ coach.phone[-4:] }}</div>
                    <div class="stat-label">手机尾号</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">{{ coach.age or '未知' }}</div>
                    <div class="stat-label">年龄</div>
                </div>
            </div>

            <!-- 操作按钮 -->
            <div class="coach-actions">
                <a href="{{ url_for('coaches.detail', id=coach.id) }}" class="btn btn-primary btn-action">
                    <i class="bi bi-eye me-1"></i>详情
                </a>

                {% if coach.status == 'pending' %}
                <a href="{{ url_for('coaches.approve', id=coach.id) }}" class="btn btn-warning btn-action">
                    <i class="bi bi-check-circle me-1"></i>审核
                </a>
                {% endif %}

                <a href="{{ url_for('coaches.edit', id=coach.id) }}" class="btn btn-outline-secondary btn-action">
                    <i class="bi bi-pencil me-1"></i>编辑
                </a>
            </div>
        </div>
        {% endfor %}
    </div>

    <!-- 分页 -->
    {% if pagination.pages > 1 %}
    <nav aria-label="教练列表分页">
        <ul class="pagination justify-content-center">
            {% if pagination.has_prev %}
            <li class="page-item">
                <a class="page-link" href="{{ url_for('coaches.list', page=pagination.prev_num, **request.args) }}">
                    <i class="bi bi-chevron-left"></i>
                </a>
            </li>
            {% endif %}

            {% for page_num in pagination.iter_pages() %}
                {% if page_num %}
                    {% if page_num != pagination.page %}
                    <li class="page-item">
                        <a class="page-link" href="{{ url_for('coaches.list', page=page_num, **request.args) }}">{{ page_num }}</a>
                    </li>
                    {% else %}
                    <li class="page-item active">
                        <span class="page-link">{{ page_num }}</span>
                    </li>
                    {% endif %}
                {% else %}
                <li class="page-item disabled">
                    <span class="page-link">…</span>
                </li>
                {% endif %}
            {% endfor %}

            {% if pagination.has_next %}
            <li class="page-item">
                <a class="page-link" href="{{ url_for('coaches.list', page=pagination.next_num, **request.args) }}">
                    <i class="bi bi-chevron-right"></i>
                </a>
            </li>
            {% endif %}
        </ul>
    </nav>
    {% endif %}

    {% else %}
    <!-- 空状态 -->
    <div class="empty-state">
        <i class="bi bi-person-x"></i>
        <h5>没有找到教练</h5>
        <p class="text-muted">尝试调整搜索条件或联系管理员</p>
    </div>
    {% endif %}
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const checkboxes = document.querySelectorAll('.coach-checkbox');
    const batchToolbar = document.getElementById('batchToolbar');
    const selectedCount = document.getElementById('selectedCount');
    const selectedIds = document.getElementById('selectedIds');
    const batchForm = document.getElementById('batchForm');

    // 复选框选择处理
    function updateSelection() {
        const selected = Array.from(checkboxes).filter(cb => cb.checked);
        const count = selected.length;
        const ids = selected.map(cb => cb.value);

        selectedCount.textContent = count;
        selectedIds.value = ids.join(',');

        if (count > 0) {
            batchToolbar.classList.add('active');
        } else {
            batchToolbar.classList.remove('active');
        }
    }

    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelection);
    });

    // 批量操作表单处理
    const actionSelect = batchForm.querySelector('select[name="action"]');
    const levelField = document.getElementById('levelField');
    const campusField = document.getElementById('campusField');

    actionSelect.addEventListener('change', function() {
        levelField.style.display = this.value === 'set_level' ? 'block' : 'none';
        campusField.style.display = this.value === 'transfer_campus' ? 'block' : 'none';
    });

    // 清除选择
    window.clearSelection = function() {
        checkboxes.forEach(cb => cb.checked = false);
        updateSelection();
    };

    // 批量操作确认
    batchForm.addEventListener('submit', function(e) {
        const action = actionSelect.value;
        const count = parseInt(selectedCount.textContent);

        let confirmText = '';
        switch (action) {
            case 'activate':
                confirmText = `确定要激活选中的 ${count} 个教练吗？`;
                break;
            case 'deactivate':
                confirmText = `确定要停用选中的 ${count} 个教练吗？`;
                break;
            case 'set_level':
                const level = this.querySelector('select[name="target_level"]').value;
                if (!level) {
                    alert('请选择目标级别');
                    e.preventDefault();
                    return;
                }
                confirmText = `确定要将选中的 ${count} 个教练设置为指定级别吗？`;
                break;
            case 'transfer_campus':
                const campus = this.querySelector('select[name="target_campus_id"]').value;
                if (!campus) {
                    alert('请选择目标校区');
                    e.preventDefault();
                    return;
                }
                confirmText = `确定要将选中的 ${count} 个教练转移到指定校区吗？`;
                break;
            case 'delete':
                confirmText = `确定要删除选中的 ${count} 个教练吗？此操作不可撤销！`;
                break;
            default:
                alert('请选择批量操作类型');
                e.preventDefault();
                return;
        }

        if (!confirm(confirmText)) {
            e.preventDefault();
        }
    });

    // 搜索表单自动提交
    const searchForm = document.getElementById('searchForm');
    const searchInputs = searchForm.querySelectorAll('select, input');

    searchInputs.forEach(input => {
        if (input.type === 'text') {
            // 文本输入框延迟提交
            let timeout;
            input.addEventListener('input', function() {
                clearTimeout(timeout);
                timeout = setTimeout(() => {
                    searchForm.submit();
                }, 500);
            });
        } else {
            // 下拉框立即提交
            input.addEventListener('change', function() {
                searchForm.submit();
            });
        }
    });

    // 卡片点击跳转到详情页
    document.querySelectorAll('.coach-card').forEach(card => {
        card.addEventListener('click', function(e) {
            // 如果点击的是复选框或按钮，不跳转
            if (e.target.type === 'checkbox' || e.target.closest('.coach-actions') || e.target.closest('.btn')) {
                return;
            }

            const coachId = this.dataset.coachId;
            window.location.href = `/coaches/${coachId}`;
        });
    });
});
</script>
{% endblock %}